import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

// 创建axios实例
const service = axios.create({
  baseURL: '', // 由vue.config.js代理处理
  timeout: 10000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
     /*const token = '123456';
    console.log('Request token:', token);*/

    /*if (token) {
      // 设置请求头
      config.headers = {
        ...config.headers,
        'Authorization': token
      };
      console.log('Request headers:', config.headers);
    }*/
    return config;
  },
  error => {
    console.error('Request error:', error);
    return Promise.reject(error);
  }
);

// 用于控制登录过期提示只弹一次
let isTokenExpiredMessageVisible = false;

// response拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;
    console.log('Response data:', res); // 添加日志

    if (res.code !== 0) {
      // token 相关错误
      if ([401].includes(res.code)) {
        if (!isTokenExpiredMessageVisible) {
          isTokenExpiredMessageVisible = true;
          Message({
            message: '登录状态已过期，请重新登录',
            type: 'error',
            duration: 5 * 1000,
            onClose: () => {
              isTokenExpiredMessageVisible = false;
            }
          });
          store.dispatch('user/logout');
          router.push('/login');
        }
      }
      return Promise.reject(new Error(res.msg || 'Error'));
    }
    return res;
  },
  error => {
    console.error('Response error:', error);
    let message = '网络错误';
    if (error.response && error.response.data && error.response.data.msg) {
      message = error.response.data.msg;
    } else if (error.msg) {
      message = error.msg;
    }
    Message.error(message);
    return Promise.reject(error);
  }
);

export default service
